import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Table,
  Row,
  Col,
  Statistic,
  Space,
  Input,
  Select,
  Button,
  Modal,
  Form,
  Tag,
  Popconfirm,
  message,
  Drawer,
  Tooltip
} from 'antd';
import {
  DatabaseOutlined,
  ShareAltOutlined,
  NodeIndexOutlined,
  PlusOutlined,
  SearchOutlined,
  FilterOutlined,
  UploadOutlined,
  DownloadOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { entityApi as entityService, entityTypeApi } from '../../../services/api';
import EntityTypeManager from '../../../components/EntityTypeManager';

const { Search } = Input;
const { Option } = Select;
const { confirm } = Modal;

/**
 * 实体管理组件
 */
const DataManagement = () => {
  // 状态定义
  const [entities, setEntities] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [editing, setEditing] = useState(null);
  const [current, setCurrent] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [stats, setStats] = useState({
    entityCount: 0,
    relationCount: 0,
    typeCount: 0
  });
  const [typeDistribution, setTypeDistribution] = useState([]);
  const [activityTrend, setActivityTrend] = useState({});
  const [timeDimension, setTimeDimension] = useState('周');
  const [entityTypes, setEntityTypes] = useState([]);
  const [isTypeModalVisible, setIsTypeModalVisible] = useState(false);
  const [typeForm] = Form.useForm();
  const fileInputRef = useRef(null);

  // 获取实体列表
  const fetchEntities = async (params = {}) => {
    setLoading(true);
    try {
      // 合并查询参数（只查询当前用户的实体）
      const queryParams = {
        page: params.page || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
        searchText,
        type: filterType !== 'all' ? filterType : undefined,
        onlyCurrentUser: true, // 只查询当前用户的实体
        ...params
      };
      
      console.log('发送请求参数:', queryParams);
      const response = await entityService.getEntities(queryParams);
      console.log('后端响应:', response);
      
      // 处理后端返回的数据
      if (response && response.success && response.data) {
        const { data: entityList, total, current, pageSize } = response.data;
        
        // 格式化时间字段并去重
        const formattedEntities = entityList
          .filter((entity, index, self) => 
            index === self.findIndex(e => e.id === entity.id)
          )
          .map(entity => ({
            ...entity,
            createTime: entity.createTime ? new Date(entity.createTime).toLocaleDateString() : '',
            updateTime: entity.updateTime ? new Date(entity.updateTime).toLocaleDateString() : '',
            relationCount: entity.relationCount || 0
          }));
        
        setEntities(formattedEntities);
        setPagination({
          current: current || 1,
          pageSize: pageSize || 10,
          total: total || 0
        });
      } else {
        // 如果后端返回失败，显示错误信息
        message.error(response?.message || '获取实体列表失败');
        setEntities([]);
        setPagination({
          current: 1,
          pageSize: 10,
          total: 0
        });
      }
    } catch (error) {
      console.error('获取实体列表失败:', error);
      message.error('网络错误，无法获取实体列表');
      setEntities([]);
      setPagination({
        current: 1,
        pageSize: 10,
        total: 0
      });
    } finally {
      setLoading(false);
    }
  };

  // 获取实体类型列表（当前用户的）
  const fetchEntityTypes = async () => {
    try {
      console.log('获取当前用户的实体类型列表...');
      // 直接使用启用的类型接口，因为用户专属接口可能不存在
      const response = await entityTypeApi.getEnabledEntityTypes();
      console.log('实体类型响应:', response);
      
      if (response && response.success && response.data) {
        const types = response.data.map(type => ({
          value: type.typeCode,
          label: type.typeName,
          color: type.color
        }));
        setEntityTypes(types);
      } else {
        setEntityTypes([]);
      }
    } catch (error) {
      console.error('获取实体类型失败:', error);
      setEntityTypes([]);
    }
  };

  // 获取统计数据（当前用户的）
  const fetchStats = async () => {
    try {
      console.log('获取当前用户的统计数据...');
      // 先尝试获取用户统计，如果失败则获取全局统计
      let response;
      try {
        response = await entityService.getUserStats();
      } catch (userStatsError) {
        console.log('用户统计接口不可用，使用全局统计');
        response = await entityService.getStats();
      }
      
      console.log('统计数据响应:', response);
      console.log('统计数据详情:', JSON.stringify(response.data, null, 2));
      
      if (response && response.success && response.data) {
        setStats({
          entityCount: response.data.entityCount || 0,
          relationCount: response.data.relationCount || 0,
          typeCount: response.data.typeCount || 0
        });
        
        // 检查typeDistribution的格式
        if (response.data.typeDistribution) {
          console.log('类型分布数据:', JSON.stringify(response.data.typeDistribution, null, 2));
          setTypeDistribution(response.data.typeDistribution);
        } else {
          console.warn('类型分布数据为空');
          setTypeDistribution([]);
        }
        
        // 检查activityTrend的格式
        if (response.data.activityTrend) {
          console.log('活跃度趋势数据:', JSON.stringify(response.data.activityTrend, null, 2));
          setActivityTrend(response.data.activityTrend);
        } else {
          console.warn('活跃度趋势数据为空');
          setActivityTrend({});
        }
      } else {
        message.error(response?.message || '获取统计数据失败');
        setStats({ entityCount: 0, relationCount: 0, typeCount: 0 });
        setTypeDistribution([]);
        setActivityTrend({});
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
      message.error('网络错误，无法获取统计数据');
      setStats({ entityCount: 0, relationCount: 0, typeCount: 0 });
      setTypeDistribution([]);
      setActivityTrend({});
    }
  };

  // 初始化加载
  useEffect(() => {
    fetchEntityTypes();
    fetchEntities();
    fetchStats();
  }, []);

  // 搜索或筛选条件变化时重新加载
  useEffect(() => {
    fetchEntities({ page: 1 }); // 重置到第一页
  }, [searchText, filterType]);

  // 表格分页、排序、筛选变化时的回调
  const handleTableChange = (pagination) => {
    setPagination(pagination);
    fetchEntities({
      page: pagination.current,
      pageSize: pagination.pageSize
    });
  };

  // 查看详情
  const handleViewDetails = async (record) => {
    try {
      setLoading(true);
      console.log('获取实体详情:', record.id);
      const response = await entityService.getEntityById(record.id);
      console.log('详情响应:', response);
      
      if (response && response.success && response.data) {
        setCurrent({
          ...response.data,
          createTime: response.data.createTime ? new Date(response.data.createTime).toLocaleString() : '',
          updateTime: response.data.updateTime ? new Date(response.data.updateTime).toLocaleString() : ''
        });
      } else {
        // 如果API调用失败，使用表格中的数据
        setCurrent(record);
      }
    } catch (error) {
      console.error('获取详情失败:', error);
      // 如果API调用失败，使用表格中的数据
      setCurrent(record);
    } finally {
      setIsDrawerVisible(true);
      setLoading(false);
    }
  };

  // 编辑实体
  const handleEdit = (record) => {
    setEditing(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  // 删除实体
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      console.log('删除实体:', id);
      const response = await entityService.deleteEntity(id);
      console.log('删除响应:', response);
      
      if (response && response.success) {
        message.success(response.message || '删除成功');
        fetchEntities(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error(error.message || '删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 添加实体
  const handleAdd = () => {
    setEditing(null);
    form.resetFields();
    
    // 如果有实体类型，默认选择第一个
    if (entityTypes.length > 0) {
      form.setFieldsValue({ type: entityTypes[0].value });
    }
    
    setIsModalVisible(true);
  };

  // 保存实体（添加或更新）
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      console.log('保存实体数据:', values);
      
      let response;
      if (editing) {
        // 更新实体
        response = await entityService.updateEntity(editing.id, values);
        console.log('更新响应:', response);
      } else {
        // 创建新实体
        response = await entityService.createEntity(values);
        console.log('创建响应:', response);
      }
      
      if (response && response.success) {
        message.success(response.message || (editing ? '更新成功' : '添加成功'));
        setIsModalVisible(false);
        fetchEntities(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '操作失败');
      }
    } catch (error) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      console.error('保存失败:', error);
      message.error(error.message || '操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (!selectedRowKeys.length) return;
    
    confirm({
      title: '确认批量删除',
      icon: <ExclamationCircleOutlined />,
      content: `您确定要删除选中的 ${selectedRowKeys.length} 条记录吗？删除后数据将无法恢复。`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        try {
          setLoading(true);
          console.log('批量删除实体:', selectedRowKeys);
          const response = await entityService.batchDeleteEntities(selectedRowKeys);
          console.log('批量删除响应:', response);
          
          if (response && response.success) {
            message.success(response.message || `成功删除 ${selectedRowKeys.length} 条记录`);
            setSelectedRowKeys([]);
            fetchEntities(); // 重新加载数据
            fetchStats();    // 更新统计数据
          } else {
            message.error(response?.message || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error(error.message || '批量删除失败');
        } finally {
          setLoading(false);
        }
      }
    });
  };

  // 导入实体
  const handleImport = () => {
    fileInputRef.current?.click();
  };

  // 处理文件上传
  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    // 检查文件类型
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.csv')) {
      message.error('只支持 Excel(.xlsx) 或 CSV(.csv) 文件');
      return;
    }
    
    try {
      setLoading(true);
      console.log('导入文件:', file.name);
      const response = await entityService.importEntities(file);
      console.log('导入响应:', response);
      
      if (response && response.success) {
        message.success(response.message || '导入成功');
        fetchEntities(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '导入失败');
      }
    } catch (error) {
      console.error('导入失败:', error);
      message.error(error.message || '导入失败');
    } finally {
      setLoading(false);
      // 重置文件输入，以便可以重新选择同一个文件
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  // 导出实体
  const handleExport = async () => {
    try {
      setLoading(true);
      
      // 构建导出参数
      const exportParams = {
        searchText,
        type: filterType !== 'all' ? filterType : undefined,
        selectedIds: selectedRowKeys.length > 0 ? selectedRowKeys : undefined
      };
      
      console.log('导出参数:', exportParams);
      const blob = await entityService.exportEntities(exportParams);
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `实体数据_${new Date().toISOString().split('T')[0]}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error(error.message || '导出失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '实体名称',
      dataIndex: 'name',
      width: 200,
      render: (text, record) => (
        <Space>
          <span style={{ fontWeight: 500 }}>{text}</span>
          <Tooltip title="查看详情">
            <EyeOutlined 
              onClick={() => handleViewDetails(record)} 
              style={{ cursor: 'pointer', color: '#1890ff', fontSize: '14px' }}
            />
          </Tooltip>
        </Space>
      )
    },
    {
      title: '实体类型',
      dataIndex: 'type',
      width: 120,
      render: t => {
        const cfg = entityTypes.find(e => e.value === t) || {};
        return <Tag color={cfg.color}>{cfg.label || t}</Tag>;
      }
    },
    { 
      title: '实体描述', 
      dataIndex: 'description', 
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          <span style={{ color: '#666' }}>{text || '暂无描述'}</span>
        </Tooltip>
      )
    },
    { 
      title: '关系数量', 
      dataIndex: 'relationCount', 
      width: 100,
      align: 'center',
      render: (count) => (
        <span style={{ 
          color: count > 0 ? '#52c41a' : '#999',
          fontWeight: count > 0 ? 500 : 'normal'
        }}>
          {count || 0}
        </span>
      )
    },
    { 
      title: '更新时间', 
      dataIndex: 'updateTime',
      width: 120,
      render: (time) => (
        <span style={{ color: '#666', fontSize: '13px' }}>{time}</span>
      )
    },
    {
      title: '操作',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="编辑">
            <EditOutlined 
              onClick={() => handleEdit(record)} 
              style={{ cursor: 'pointer', color: '#1890ff', fontSize: '16px' }}
            />
          </Tooltip>
          <Popconfirm 
            title="确认删除？" 
            description="删除后数据将无法恢复"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
            placement="topRight"
          >
            <Tooltip title="删除">
              <DeleteOutlined 
                style={{ cursor: 'pointer', color: '#ff4d4f', fontSize: '16px' }}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 统计卡片数据
  const statsData = [
    { title: '实体总数', value: stats.entityCount, icon: <DatabaseOutlined style={{ color: '#1890ff' }} />, color: '#1890ff' },
    { title: '关系总数', value: stats.relationCount, icon: <ShareAltOutlined style={{ color: '#52c41a' }} />, color: '#52c41a' },
    { title: '类型种类', value: stats.typeCount, icon: <NodeIndexOutlined style={{ color: '#faad14' }} />, color: '#faad14' }
  ];

  // 渲染类型分布图表
  const renderTypeDistributionChart = () => {
    if (typeDistribution.length === 0) {
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center', 
          height: '300px',
          color: '#999',
          fontSize: '14px'
        }}>
          暂无数据
        </div>
      );
    }
    
    return (
      <div style={{ display: 'flex', alignItems: 'center', height: '300px' }}>
        {/* 左侧饼图 */}
        <div style={{ flex: 1 }}>
          <ReactECharts
            option={{
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              series: [
                {
                  name: '实体类型',
                  type: 'pie',
                  radius: ['40%', '70%'],
                  center: ['50%', '50%'],
                  avoidLabelOverlap: false,
                  itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                  },
                  label: {
                    show: false
                  },
                  emphasis: {
                    label: {
                      show: true,
                      fontSize: '16',
                      fontWeight: 'bold'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: typeDistribution.map(item => ({
                    value: item.value,
                    name: item.type,
                    itemStyle: {
                      color: item.color
                    }
                  }))
                }
              ]
            }}
            style={{ height: '100%' }}
          />
        </div>
        
        {/* 右侧汇总信息 */}
        <div style={{ width: '140px', paddingLeft: '20px' }}>
          {typeDistribution.map((item, index) => (
            <div key={index} style={{ 
              display: 'flex', 
              alignItems: 'center', 
              marginBottom: '12px',
              fontSize: '13px'
            }}>
              <div style={{
                width: '8px',
                height: '8px',
                borderRadius: '50%',
                backgroundColor: item.color,
                marginRight: '8px'
              }} />
              <span style={{ flex: 1, color: '#666' }}>{item.type}</span>
              <span style={{ fontWeight: 'bold', color: '#333' }}>{item.value}%</span>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // 渲染活跃度趋势图表
  const renderActivityTrendChart = () => {
    if (Object.keys(activityTrend).length === 0 || !activityTrend[timeDimension]) {
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center', 
          height: '300px',
          color: '#999',
          fontSize: '14px'
        }}>
          暂无数据
        </div>
      );
    }
    
    return (
      <ReactECharts
        option={{
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['实体创建', '活跃度'],
            bottom: 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: activityTrend[timeDimension]?.categories || [],
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: {
                fontSize: 11
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '实体创建',
              position: 'left',
              axisLabel: {
                fontSize: 11,
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '活跃度',
              position: 'right',
              axisLabel: {
                fontSize: 11,
                formatter: '{value}'
              }
            }
          ],
          series: [
            {
              name: '实体创建',
              type: 'bar',
              yAxisIndex: 0,
              itemStyle: {
                borderRadius: [4, 4, 0, 0],
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#1890ff'
                    },
                    {
                      offset: 1,
                      color: '#69c0ff'
                    }
                  ]
                }
              },
              data: activityTrend[timeDimension]?.barData || []
            },
            {
              name: '活跃度',
              type: 'line',
              yAxisIndex: 1,
              smooth: true,
              lineStyle: {
                width: 3,
                color: '#722ed1'
              },
              itemStyle: {
                color: '#722ed1'
              },
              symbol: 'circle',
              symbolSize: 6,
              data: activityTrend[timeDimension]?.lineData || []
            }
          ]
        }}
        style={{ height: '300px' }}
      />
    );
  };

  return (
    <div style={{ padding: 24, background: '#f5f5f5' }}>
      <style jsx>{`
        .table-row-light {
          background-color: #fafafa;
        }
        .table-row-dark {
          background-color: #ffffff;
        }
        .table-row-light:hover,
        .table-row-dark:hover {
          background-color: #e6f7ff !important;
        }
        .ant-table-thead > tr > th {
          background-color: #f0f2f5;
          font-weight: 600;
          color: #262626;
          border-bottom: 2px solid #d9d9d9;
        }
        .ant-table-tbody > tr > td {
          padding: 12px 16px;
          border-bottom: 1px solid #f0f0f0;
        }
        .ant-table-tbody > tr:last-child > td {
          border-bottom: none;
        }
      `}</style>
      {/* 统计 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        {statsData.map((s, idx) => (
          <Col key={idx} span={8}>
            <Card style={{ borderRadius: 8 }}>
              <Statistic title={s.title} value={s.value} prefix={s.icon} valueStyle={{ color: s.color }}/>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 图表 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} md={12}>
          <Card title="实体类型分布" style={{ borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
            {renderTypeDistributionChart()}
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card 
            title="实体活跃度趋势" 
            style={{ borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}
            extra={
              <Space>
                {['周', '月', '年'].map(period => (
                  <Button
                    key={period}
                    type={timeDimension === period ? 'primary' : 'default'}
                    size="small"
                    onClick={() => setTimeDimension(period)}
                  >
                    {period}
                  </Button>
                ))}
              </Space>
            }
          >
            {renderActivityTrendChart()}
          </Card>
        </Col>
      </Row>

      {/* 列表和操作 */}
      <Card title="实体管理" style={{ borderRadius: 8 }} extra={
        <Space>
          <Select value={filterType} onChange={setFilterType} style={{ width: 120 }} suffixIcon={<FilterOutlined />}>
            <Option value="all">全部类型</Option>
            {entityTypes.map(e => (
              <Option key={e.value} value={e.value}>{e.label}</Option>
            ))}
          </Select>
          <Search placeholder="搜索" allowClear onSearch={setSearchText} style={{ width: 200 }} />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加</Button>
          <Button icon={<UploadOutlined />} onClick={handleImport}>导入</Button>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>导出</Button>
          <Button icon={<NodeIndexOutlined />} onClick={() => setIsTypeModalVisible(true)}>类型管理</Button>
        </Space>
      }>
        {selectedRowKeys.length > 0 && (
          <div style={{ marginBottom: 16, padding: 8, background: '#e6f7ff', borderRadius: 6 }}>
            已选择 {selectedRowKeys.length} 项
            <Space style={{ float: 'right' }}>
              <Button onClick={() => setSelectedRowKeys([])}>取消</Button>
              <Button danger onClick={handleBatchDelete}>批量删除</Button>
            </Space>
          </div>
        )}
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={entities}
          rowSelection={{ 
            selectedRowKeys, 
            onChange: setSelectedRowKeys,
            columnWidth: 50
          }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            showLessItems: true
          }}
          onChange={handleTableChange}
          scroll={{ x: 1000 }}
          size="middle"
          bordered={false}
          rowClassName={(record, index) => 
            index % 2 === 0 ? 'table-row-light' : 'table-row-dark'
          }
        />
      </Card>

      {/* 添加/编辑 弹窗 */}
      <Modal
        title={editing ? '编辑实体' : '添加实体'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
        confirmLoading={loading}
      >
        <Form form={form} layout="vertical" initialValues={{ type: '' }}>
          <Form.Item name="name" label="名称" rules={[{ required: true, message: '请输入实体名称' }]}>
            <Input placeholder="请输入实体名称" />
          </Form.Item>
          <Form.Item name="type" label="类型" rules={[{ required: true, message: '请选择实体类型' }]}>
            <Select placeholder="请选择实体类型">
              {entityTypes.map(e => (
                <Option key={e.value} value={e.value}>
                  <Tag color={e.color}>{e.label}</Tag>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea rows={3} placeholder="请输入实体描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 详情 抽屉 */}
      <Drawer
        title="实体详情"
        width={400}
        open={isDrawerVisible}
        onClose={() => setIsDrawerVisible(false)}
      >
        {current && (
          <div>
            <h3>{current.name}</h3>
            <Tag color={entityTypes.find(e => e.value === current.type)?.color}>
              {entityTypes.find(e => e.value === current.type)?.label}
            </Tag>
            <p style={{ margin: '16px 0' }}>{current.description}</p>
            <p>关系数：{current.relationCount}</p>
            <p>创建时间：{current.createTime}</p>
            <p>更新时间：{current.updateTime}</p>
          </div>
        )}
      </Drawer>

      {/* 类型管理 Modal */}
      <Modal
        title="实体类型管理"
        open={isTypeModalVisible}
        onCancel={() => setIsTypeModalVisible(false)}
        width={800}
        footer={[
          <Button key="close" onClick={() => setIsTypeModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        <EntityTypeManager onTypeChange={fetchEntityTypes} />
      </Modal>

      {/* 隐藏的文件上传输入 */}
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        accept=".xlsx,.csv"
        onChange={handleFileUpload}
      />
    </div>
  );
};

export default DataManagement;
